import router from '@/router'

import { RouteRecordRaw } from 'vue-router'

import layout from '@/layout/index.vue'

interface menuStore {
  menuList: any[]
  fistMenu: string
}

export const useMenuStore = defineStore('menuList', {
  state: (): menuStore => ({
    menuList: [],
    fistMenu: '',
  }),
  actions: {
    // 设置菜单列表及默认打开的菜单(首页)
    setMenu(menuList: any[], firstMenu: string) {
      this.menuList = menuList
      this.fistMenu = firstMenu
      this.setMenuList()
    },
    setMenuList() {
      const list = JSON.parse(JSON.stringify(this.menuList))
      // 导入vue文件
      const modules = import.meta.glob('../../views/**/**/*.vue')

      //  递归遍历菜单列表,将vue文件注入
      function initMenuList(list: any[]) {
        list.forEach((item: any) => {
          if (item.component) {
            const link = modules[`../../views/${item.component}.vue`]
            item.component = link
          }
          if (item.children) {
            initMenuList(item.children)
          }
        })
      }
      initMenuList(list)

      // 将菜单列表添加到路由中,name为layout
      const newMenu: RouteRecordRaw = {
        path: '/',
        component: layout,
        name: 'layout',
        children: [...list],
      }
      // 将所有菜单添加到main路由下
      router.addRoute('main', newMenu)
    },

    removeMenuList() {
      this.menuList = []
      this.fistMenu = ''
      // 删除layout路由
      router.removeRoute('layout')
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'menuList',
        storage: localStorage,
      },
    ],
  },
})
